section .data
	n:dq 0
	len:dq 0
	addr: dq 0
	p:dq 2
	max:dq 0
	i:dq 2

%define mk64 0x2000000+

section .text
	global _sieve
_sieve:
	push rbp
	push rbx
	push rcx
	mov rbp,rsp
	mov [rel n],rdi			;save 1st arg to n

	inc rdi
	mov [rel len],rdi			;mmap len = n + 1
	mov rax,mk64 197				;call syscall mmap
	mov rdi,0
	mov rsi,[rel len]
	mov rdx,3
	mov r10,0x1001
	mov r8,-1
	mov r9,0
	syscall
	;cmp rax,0xfffffffffffff001		;mmap error
	;jb next
	cmp rax,0xfff
	ja next
	mov rax,-1			;return -1
	jmp quit
next:
	;int 3
	mov [rel addr],rax			;save mmap return addr
					;FIXME:mmap space always 0 ???
	fild qword [rel n]			;calc sqrt(n) and save result to max
	fsqrt
	;fstp qword [max]
	fistp qword [rel max]
	;fistp r14
	;inc qword [max]
	mov r15,[rel p]			;r15 = p
	mov r14,[rel max]			;r14 = max
	mov r13,[rel n]			;r13 = n
	mov r12,[rel i]			;r12 = i
enter_while:
	;mov rcx,[p]
	cmp r15,r14			;if p<=max
	ja quit_while
	;mov rbx,[p]
	mov rbx,r15
	shl rbx,1
	;mov [i],rbx
	mov r12,rbx
enter_for:				
	;mov rcx,[i]
	;cmp rcx,[n]
	cmp r12,r13
	ja quit_for

	;mov r15,[addr]
	;mov byte [rax + rcx],1
	mov byte [rax + r12],1

	;mov rcx,[p]
	;add [i],r15
	add r12,r15
	jmp enter_for
	;xor rcx,rcx
quit_for:
	;inc qword [p]
	inc r15
	;mov rbx,[p]
	;mov r15,[addr]
	mov cl,byte [rax + r15]
	test cl,cl
	jnz quit_for

	jmp enter_while
	;xor rcx,rcx
quit_while:
	;mov rbx,[n]
	;mov r15,[addr]
	;mov cl,byte [rax + rbx]
	mov cl,byte [rax + r13]
	test cl,cl
	jz pre_quit
	;dec qword [n]
	dec r13
	jmp quit_while
pre_quit:
	mov rax,r13
quit:
	mov rsp,rbp
	pop rcx
	pop rbx
	pop rbp
	ret

